import { defineStore } from 'pinia'
import { ref } from 'vue'
import { favoriteAPI } from '@/api'

export const useFavoriteStore = defineStore('favorite', () => {
  // 状态
  const favoriteStatus = ref(new Map()) // 存储商品ID -> 是否收藏的状态
  const favoriteCounts = ref(new Map()) // 存储商品ID -> 收藏数量

  // 检查商品是否被收藏
  const isFavorite = (productId) => {
    return favoriteStatus.value.get(productId) || false
  }

  // 获取商品收藏数量
  const getFavoriteCount = (productId) => {
    const count = favoriteCounts.value.get(productId)
    return count !== undefined && count !== null ? count : 0
  }

  // 设置商品收藏状态
  const setFavoriteStatus = (productId, isFav) => {
    favoriteStatus.value.set(productId, isFav)
  }

  // 设置商品收藏数量
  const setFavoriteCount = (productId, count) => {
    favoriteCounts.value.set(productId, count)
  }

  // 检查收藏状态（从服务器获取）
  const checkFavoriteStatus = async (productId) => {
    try {
      const response = await favoriteAPI.checkFavorite(productId)
      if (response.code === 0) {
        setFavoriteStatus(productId, response.data)
        return response.data
      }
      return false
    } catch (error) {
      console.error('检查收藏状态失败:', error)
      return false
    }
  }

  // 获取收藏数量（从服务器获取）
  const fetchFavoriteCount = async (productId) => {
    try {
      const response = await favoriteAPI.getFavoriteCount(productId)
      if (response.code === 0) {
        setFavoriteCount(productId, response.data)
        return response.data
      }
      return 0
    } catch (error) {
      console.error('获取收藏数量失败:', error)
      return 0
    }
  }

  // 切换收藏状态
  const toggleFavorite = async (productId) => {
    try {
      const isFav = isFavorite(productId)
      const response = isFav 
        ? await favoriteAPI.removeFavorite(productId)
        : await favoriteAPI.addFavorite(productId)

      if (response.code === 0) {
        // 更新本地状态
        setFavoriteStatus(productId, !isFav)
        
        // 更新收藏数量
        const currentCount = getFavoriteCount(productId)
        const newCount = isFav ? Math.max(0, currentCount - 1) : currentCount + 1
        setFavoriteCount(productId, newCount)

        // 触发全局事件，通知其他组件更新
        window.dispatchEvent(new CustomEvent('favoriteStatusChanged', {
          detail: { productId, isFavorite: !isFav, count: getFavoriteCount(productId) }
        }))

        return { success: true, isFavorite: !isFav }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('切换收藏状态失败:', error)
      return { success: false, message: '操作失败，请重试' }
    }
  }

  // 批量更新收藏状态（用于收藏页面）
  const updateFavoriteStatuses = (favorites) => {
    favorites.forEach(favorite => {
      setFavoriteStatus(favorite.productId, true)
    })
  }

  // 清除指定商品的收藏状态
  const clearFavoriteStatus = (productId) => {
    favoriteStatus.value.delete(productId)
    favoriteCounts.value.delete(productId)
  }

  // 清除所有收藏状态
  const clearAllFavoriteStatus = () => {
    favoriteStatus.value.clear()
    favoriteCounts.value.clear()
  }

  // 清理已售商品的收藏数据
  const cleanSoldProductFromFavorites = async (productId) => {
    try {
      console.log('FavoriteStore: 开始清理已售商品的收藏数据:', productId)
      
      // 如果商品在收藏中，移除收藏
      if (isFavorite(productId)) {
        await toggleFavorite(productId)
        console.log('FavoriteStore: 已从收藏中移除已售商品:', productId)
      }
    } catch (error) {
      console.error('FavoriteStore: 清理已售商品收藏数据失败:', error)
    }
  }

  return {
    // 状态
    favoriteStatus,
    favoriteCounts,
    
    // 方法
    isFavorite,
    getFavoriteCount,
    setFavoriteStatus,
    setFavoriteCount,
    checkFavoriteStatus,
    fetchFavoriteCount,
    toggleFavorite,
    updateFavoriteStatuses,
    clearFavoriteStatus,
    clearAllFavoriteStatus,
    cleanSoldProductFromFavorites
  }
})
